package com.mico.micochange.account;

import com.alibaba.fastjson.JSONObject;
import com.mico.micochange.common.ExchangeCacheUtils;
import com.mico.micochange.server.MicoThread;
import com.mico.xchange.Exchange;
import com.mico.xchange.ExchangeFactory;
import com.mico.xchange.binance.BinanceExchange;
import com.mico.xchange.binance.service.BinanceAccountService;
import com.mico.xchange.bitstamp.BitstampExchange;
import com.mico.xchange.bitstamp.dto.account.BitstampBalance;
import com.mico.xchange.bitstamp.service.BitstampAccountServiceRaw;
import com.mico.xchange.bitz.BitZExchange;
import com.mico.xchange.bitz.service.BitZBaseService;
import com.mico.xchange.chaoex.ChaoexExchange;
import com.mico.xchange.chaoex.ChaoexUtils;
import com.mico.xchange.chaoex.dto.account.ChaoexBalance;
import com.mico.xchange.chaoex.dto.account.results.ChaoexAccountResult;
import com.mico.xchange.chaoex.dto.trade.ChaoexLogin;
import com.mico.xchange.chaoex.service.ChaoexAccountServiceRaw;
import com.mico.xchange.currency.Currency;
import com.mico.xchange.dto.account.AccountInfo;
import com.mico.xchange.dto.account.Balance;
import com.mico.xchange.fcoin.FCoinExchange;
import com.mico.xchange.fcoin.dto.trade.FCoinBalance;
import com.mico.xchange.fcoin.service.FCoinTradeServiceRaw;
import com.mico.xchange.huobi.HuobiExchange;
import com.mico.xchange.huobi.service.HuobiAccountService;
import com.mico.xchange.okcoin.OkCoinExchange;
import com.mico.xchange.okcoin.dto.account.OkCoinFunds;
import com.mico.xchange.okcoin.service.OkCoinAccountServiceRaw;
import org.apache.mina.core.session.IoSession;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by chenst on 2018/5/6.
 */
public class AccountQueryThread extends MicoThread{

    public AccountQueryThread(IoSession session, String message) {
        super(session, message);
    }

    @Override
    public Map doHuobiChange(JSONObject json)  throws Exception{

        Exchange exchange = ExchangeCacheUtils.getExchange(HuobiExchange.class.getName(), json.get("apiKey").toString(), json.get("secretKey").toString());
        HuobiAccountService accountService = (HuobiAccountService) exchange.getAccountService();
        Map<String,Balance> retMap = new HashMap<String,Balance>();
        Map<Currency,Balance> balanceMap = new HashMap<Currency,Balance>();
        //账户查询
        AccountInfo acc = null;
        if("1".equals(json.getString("hadax"))){
            acc = accountService.getHadaxAccountInfo();
        }else {
            acc = accountService.getAccountInfo();
        }
        balanceMap = acc.getWallet().getBalances();
        for(Currency currency : balanceMap.keySet()){
            if(balanceMap.get(currency).getTotal().compareTo(new BigDecimal(0))>0){
                Balance balance = balanceMap.get(currency);
                balance.setCurrency(null);
                retMap.put(currency.getCurrencyCode(),balance);
            }
        }
        return retMap;
    }

    @Override
    public Map doBinanceChange(JSONObject json) throws Exception{
        Exchange exchange = ExchangeCacheUtils.getExchange(BinanceExchange.class.getName(), json.get("apiKey").toString(), json.get("secretKey").toString());
        //账户信息
        BinanceAccountService accountService = (BinanceAccountService) exchange.getAccountService();
        Map<String,Balance> retMap = new HashMap<String,Balance>();
        Map<Currency,Balance> balanceMap = new HashMap<Currency,Balance>();

        //账户查询
        AccountInfo acc = accountService.getAccountInfo();
        balanceMap = acc.getWallet().getBalances();
        for(Currency currency : balanceMap.keySet()){
            if(balanceMap.get(currency).getTotal().compareTo(new BigDecimal(0))>0){
                Balance balance = balanceMap.get(currency);
                balance.setCurrency(null);
                retMap.put(currency.getCurrencyCode(),balance);
            }
        }
        return retMap;
    }

    @Override
    public Map doChaoexChange(JSONObject json) throws Exception{
        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(ChaoexExchange.class.getName(), json.get("apiKey").toString(), json.get("secretKey").toString());
        ChaoexAccountServiceRaw chaoexAccountService = (ChaoexAccountServiceRaw)exchange.getAccountService();
        ChaoexLogin chaoexLogin = ChaoexUtils.getToken(json.get("apiKey").toString(),json.get("secretKey").toString(),json.get("loginPwd").toString());
        ChaoexAccountResult result = chaoexAccountService.account(chaoexLogin.getUid(),chaoexLogin.getToken());

        //防止token超时
        if("9999".equals(result.getStatus())){
            chaoexLogin = ChaoexUtils.getNewToken(json.get("apiKey").toString(),json.get("secretKey").toString(),json.get("loginPwd").toString());
            result = chaoexAccountService.account(chaoexLogin.getUid(),chaoexLogin.getToken());
        }else if(!result.isSuccess()){
            throw new Exception(result.getError());
        }

        List<ChaoexBalance> list =  new ArrayList<ChaoexBalance>();
        if(result!=null && result.getResult()!=null && result.getResult().getCoinList()!=null){
            list = result.getResult().getCoinList();
        }else{
            throw new Exception("余额获取失败");
        }
        Map<String,Balance> retMap = new HashMap<String,Balance>();
        for(ChaoexBalance balance : list){
            if(balance.getAmount()!=null && balance.getAmount().compareTo(new BigDecimal(0))>0) {
                Balance var = new Balance(null, balance.getAmount(), balance.getAmount().subtract(balance.getFreezeAmount()), balance.getFreezeAmount());
                if (balance.getAmount().compareTo(new BigDecimal(0)) > 0)
                    var.setClose(balance.getBtc_value().divide(balance.getAmount(), 8,BigDecimal.ROUND_HALF_DOWN));
                retMap.put(balance.getCurrencyNameEn(), var);
            }
        }
        return retMap;
    }

    @Override
    public Map doBitstampChange(JSONObject json) throws Exception{
        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(BitstampExchange.class.getName(), json.get("apiKey").toString(), json.get("secretKey").toString());
        BitstampAccountServiceRaw accountServiceRaw = (BitstampAccountServiceRaw)exchange.getAccountService();
        BitstampBalance result = accountServiceRaw.getBitstampBalance();
        Collection<BitstampBalance.Balance> balances =  result.getBalances();
        Map<String,Balance> retMap = new HashMap<String,Balance>();
        for(BitstampBalance.Balance balance : balances){
            Balance var = new Balance(null,balance.getBalance(),balance.getAvailable(),balance.getReserved());
            retMap.put(balance.getCurrency(),var);
        }
        return retMap;
    }

    @Override
    public Map doOkexChange(JSONObject json) throws Exception {
        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(OkCoinExchange.class.getName(),json.get("apiKey").toString(), json.get("secretKey").toString());
        OkCoinAccountServiceRaw accountService = (OkCoinAccountServiceRaw)exchange.getAccountService();
        OkCoinFunds okCoinFunds = accountService.getUserInfo().getInfo().getFunds();
        Map<String,BigDecimal> free = okCoinFunds.getFree();
        Map<String,Balance> retMap = new HashMap<String,Balance>();
        for(String key : free.keySet()){
            Balance var = new Balance(null,free.get(key).add(okCoinFunds.getFreezed().get(key)),free.get(key),okCoinFunds.getFreezed().get(key));
            retMap.put(key,var);
        }
        return retMap;
    }

    @Override
    public Map doFCoinExchange(JSONObject json) throws Exception {

        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(FCoinExchange.class.getName(),json.get("apiKey").toString(), json.get("secretKey").toString());
        FCoinTradeServiceRaw tradeService = (FCoinTradeServiceRaw)exchange.getTradeService();
        List<FCoinBalance> list = tradeService.getBalance();
        Map<String,Balance> retMap = new HashMap<String,Balance>();
        for(FCoinBalance balance : list){
            if(balance.getBalance().compareTo(new BigDecimal(0))>0) {
                Balance var = new Balance(null, balance.getBalance(), balance.getAvailable(), balance.getFrozen());
                retMap.put(balance.getCurrency().toUpperCase(), var);
            }
        }
        return retMap;
    }


}
